﻿namespace TradePublish.Common
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Text.RegularExpressions;

    public class GetData
    {
        private static Encoding GetEncoding(string html)
        {
            string pattern = @"(?i)\bcharset=(?<charset>[-a-zA-Z_0-9]+)";
            string name = Regex.Match(html, pattern).Groups["charset"].Value;
            try
            {
                return Encoding.GetEncoding(name);
            }
            catch (ArgumentException)
            {
                return null;
            }
        }
        public string GetResponse(string url, IDictionary<string, string> parameters)
        {
            return GetResponse(url, parameters,3);
        }
        /// <summary>
        /// 避免死循环，跳转最多三次
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="iniStep"></param>
        /// <returns></returns>
        public string GetResponse(string url, IDictionary<string, string> parameters,int iniStep)
        {
            int num2;
            Exception exception2;
            int num = new Random().Next(0, 0x3e8);
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            StringBuilder builder = new StringBuilder();
            if ((parameters != null) && (parameters.Count != 0))
            {
                num2 = 0;
                foreach (string str in parameters.Keys)
                {
                    if (num2 > 0)
                    {
                        builder.AppendFormat("&{0}={1}", str, Uri.EscapeDataString(parameters[str]));
                    }
                    else
                    {
                        builder.AppendFormat("?{0}={1}", str, Uri.EscapeDataString(parameters[str]));
                    }
                    num2++;
                }
            }
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Encoding encoding = null;
            string input = null;
            try
            {
                TextReader reader;
                Exception exception;
                request = (HttpWebRequest) WebRequest.Create(url + builder.ToString());
                request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75";
                request.Timeout = 0x4e20;
                response = (HttpWebResponse) request.GetResponse();
                string str3 = response.Headers["Content-Type"];
                Regex regex = new Regex(@"charset\s*=\s*(\S+)", RegexOptions.IgnoreCase);
                Match match = null;
                if (str3 != null)
                {
                    match = regex.Match(str3);
                    if (match.Success)
                    {
                        try
                        {
                            encoding = Encoding.GetEncoding(match.Groups[1].Value.Trim().Replace("\"", ""));
                            using (reader = new StreamReader(response.GetResponseStream(), encoding))
                            {
                                input = reader.ReadToEnd();
                            }
                        }
                        catch (Exception exception1)
                        {
                            exception = exception1;
                            throw exception;
                        }
                    }
                }
                if ((str3 == null) || !match.Success)
                {
                    using (reader = new StreamReader(response.GetResponseStream(), Encoding.Default))
                    {
                        input = reader.ReadToEnd();
                        match = new Regex("<\\s*meta.+charset\\s*=\\s*(\\S+)\\s*\"", RegexOptions.IgnoreCase).Match(input);
                        if (match.Success)
                        {
                            try
                            {
                                input = Encoding.GetEncoding(match.Groups[1].Value.Trim().Replace("\"", "")).GetString(Encoding.Default.GetBytes(input));
                            }
                            catch (Exception exception3)
                            {
                                exception = exception3;
                                throw exception;
                            }
                        }
                    }
                }
            }
            catch (Exception exception4)
            {
                exception2 = exception4;
                throw exception2;
            }
            finally
            {
                if (response != null)
                {
                    try
                    {
                        response.Close();
                        response = null;
                    }
                    catch (Exception exception5)
                    {
                        exception2 = exception5;
                    }
                }
                if (request != null)
                {
                    try
                    {
                        request.Abort();
                        request = null;
                    }
                    catch (Exception exception6)
                    {
                        exception2 = exception6;
                    }
                }
            }
            MatchCollection matchs = new Regex("(?<=content=\"\\w+;\\s{0,}url=)(?<content>[^\"]*)(?=\")", RegexOptions.IgnoreCase).Matches(input);
            string str4 = null;
            for (num2 = 0; num2 < matchs.Count; num2++)
            {
                str4 = matchs[num2].Groups["content"].ToString();
            }
            if (str4 == null || str4.Trim().Length == 0 || str4.Trim().Equals("#"))
            {
                return input;
            }
            if ((str4.IndexOf("http://") < 0) || (str4.IndexOf("https://") < 0))
            {
                if (str4.Substring(0, 1).Equals("/"))
                {
                    str4 = str4.Substring(1);
                }
                str4 = url.Substring(0, url.LastIndexOf("/",9)) + "/" + str4;
            }
            if (url.Equals(str4) || iniStep<=0)
            {//避免死循环。
                return input;
            }
            return this.GetResponse(str4, null, --iniStep);
        }

        public static string GetResponse(string url, IDictionary<string, string> parameters, Encoding encoding)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            StringBuilder builder = new StringBuilder();
            if ((parameters != null) && (parameters.Count != 0))
            {
                int num = 0;
                foreach (string str in parameters.Keys)
                {
                    if (num > 0)
                    {
                        builder.AppendFormat("&{0}={1}", str, Uri.EscapeDataString(parameters[str]));
                    }
                    else
                    {
                        builder.AppendFormat("?{0}={1}", str, Uri.EscapeDataString(parameters[str]));
                    }
                    num++;
                }
            }
            try
            {
                Encoding encoding2;
                byte[] bytes = new WebClient().DownloadData(url + builder.ToString());
                string html = "";
                if (encoding != null)
                {
                    html = encoding.GetString(bytes);
                    encoding2 = GetEncoding(html);
                    if ((encoding2 == null) || (encoding2 == encoding))
                    {
                        return html;
                    }
                    return encoding2.GetString(bytes);
                }
                html = Encoding.UTF8.GetString(bytes);
                encoding2 = GetEncoding(html);
                if ((encoding2 == null) || (encoding2 == Encoding.UTF8))
                {
                    return html;
                }
                return encoding2.GetString(bytes);
            }
            catch (Exception exception)
            {
               //log.Error("exception!" + exception.Message);
                return null;
            }
        }

        public string GetResponseForAlibaba(string url, IDictionary<string, string> parameters)
        {
            int num2;
            Exception exception2;
            int num = new Random().Next(0, 0x3e8);
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            StringBuilder builder = new StringBuilder();
            if ((parameters != null) && (parameters.Count != 0))
            {
                num2 = 0;
                foreach (string str in parameters.Keys)
                {
                    if (num2 > 0)
                    {

                        builder.AppendFormat("&{0}={1}", str, System.Web.HttpUtility.UrlEncode(System.Text.Encoding.Default.GetBytes(parameters[str])));
                    }
                    else
                    {
                        builder.AppendFormat("?{0}={1}", str, System.Web.HttpUtility.UrlEncode(System.Text.Encoding.Default.GetBytes(parameters[str])));
                    }
                    num2++;
                }
            }
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Encoding encoding = null;
            string input = null;
            try
            {
                TextReader reader;
                Exception exception;
                request = (HttpWebRequest)WebRequest.Create(url + builder.ToString());
                request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75";
                request.Timeout = 0x4e20;
                response = (HttpWebResponse)request.GetResponse();
                string str3 = response.Headers["Content-Type"];
                Regex regex = new Regex(@"charset\s*=\s*(\S+)", RegexOptions.IgnoreCase);
                Match match = null;
                if (str3 != null)
                {
                    match = regex.Match(str3);
                    if (match.Success)
                    {
                        try
                        {
                            encoding = Encoding.GetEncoding(match.Groups[1].Value.Trim().Replace("\"", ""));
                            using (reader = new StreamReader(response.GetResponseStream(), encoding))
                            {
                                input = reader.ReadToEnd();
                            }
                        }
                        catch (Exception exception1)
                        {
                            exception = exception1;
                            throw exception;
                        }
                    }
                }
                if ((str3 == null) || !match.Success)
                {
                    using (reader = new StreamReader(response.GetResponseStream(), Encoding.Default))
                    {
                        input = reader.ReadToEnd();
                        match = new Regex("<\\s*meta.+charset\\s*=\\s*(\\S+)\\s*\"", RegexOptions.IgnoreCase).Match(input);
                        if (match.Success)
                        {
                            try
                            {
                                input = Encoding.GetEncoding(match.Groups[1].Value.Trim().Replace("\"", "")).GetString(Encoding.Default.GetBytes(input));
                            }
                            catch (Exception exception3)
                            {
                                exception = exception3;
                                throw exception;
                            }
                        }
                    }
                }
            }
            catch (Exception exception4)
            {
                exception2 = exception4;
                throw exception2;
            }
            finally
            {
                if (response != null)
                {
                    try
                    {
                        response.Close();
                        response = null;
                    }
                    catch (Exception exception5)
                    {
                        exception2 = exception5;
                    }
                }
                if (request != null)
                {
                    try
                    {
                        request.Abort();
                        request = null;
                    }
                    catch (Exception exception6)
                    {
                        exception2 = exception6;
                    }
                }
            }
            MatchCollection matchs = new Regex("(?<=content=\"\\w+;\\s{0,}url=)(?<content>[^\"]*)(?=\")", RegexOptions.IgnoreCase).Matches(input);
            string str4 = null;
            for (num2 = 0; num2 < matchs.Count; num2++)
            {
                str4 = matchs[num2].Groups["content"].ToString();
            }
            if (str4 == null|| str4.Trim().Length == 0 || str4.Trim().Equals("#"))
            {
                return input;
            }
            if ((str4.IndexOf("http://") < 0) || (str4.IndexOf("https://") < 0))
            {
                if (str4.Substring(0, 1).Equals("/"))
                {
                    str4 = str4.Substring(1);
                }
                str4 = url.Substring(0, url.LastIndexOf("/")) + "/" + str4;
            }
            return this.GetResponse(str4, null);
        }
    
    }
}

